#include "stdafx.h"
#include "GraphicComponent.h"

GraphicComponent::GraphicComponent(Render* _render)
:vertexShader(NULL),
 pixelShader(NULL),
 geometryShader(NULL),
 vertexBuffer(NULL),
 indexBuffer(NULL),
 inputLayout(NULL)
{
	assert(_render != NULL);
	render = _render;
}

GraphicComponent::~GraphicComponent(void)
{
	if (vertexShader) render->deleteShader(Shader_Vertex, vertexShader);
	if (pixelShader) render->deleteShader(Shader_Pixel, pixelShader);
	if (inputLayout) render->deleteBuffer(Render::TYPE_LAYOUT, inputLayout);
	if (vertexBuffer) render->deleteBuffer(Render::TYPE_BUFFER, vertexBuffer);
	if (indexBuffer) render->deleteBuffer(Render::TYPE_BUFFER, indexBuffer);
}

void GraphicComponent::createVertexShader(const std::string& vsfile, const std::string& vsEntry, const VertexDesc& desc)
{
	vertexShader = render->loadShader(vsfile, Shader_Vertex, vsEntry, &inputLayout, &desc);
}

void GraphicComponent::createPixelShader(const std::string& psfile, const std::string& psEntry)
{
	pixelShader = render->loadShader(psfile, Shader_Pixel, psEntry);
}

void GraphicComponent::createGeometryShader(const std::string& gsfile, const std::string& gsEntry)
{
	geometryShader = render->loadShader(gsfile, Shader_Geometry, gsEntry);
}

void GraphicComponent::createVertexBuffer(const void* vert, size_t numElements, size_t _sizeOfVertex)
{
	sizeOfVertex = _sizeOfVertex;
	vertexBuffer = render->createVertexBuffer(vert, numElements * _sizeOfVertex);
}

void GraphicComponent::createIndexBuffer(const void* index, size_t numElements)
{
	numIndices = numElements;
	indexBuffer = render->createIndexBuffer(index, numElements * sizeof(unsigned int));
}

void GraphicComponent::draw()
{
	render->setVertexLayout(inputLayout);
	render->setVertexBuffer(vertexBuffer, sizeOfVertex, 0);
	render->setIndexBuffer(indexBuffer);

	assert(vertexShader && pixelShader);
	render->applyShader(vertexShader, Shader_Vertex);
	render->applyShader(pixelShader, Shader_Pixel);

	if (geometryShader)
	{
		render->applyShader(geometryShader, Shader_Geometry);
	}

	if (indexBuffer)
	{
		render->drawIndexBuffer(numIndices);
	}
	else
	{
		assert(vertexBuffer);
		// todo draw vertex buffer
	}
}